import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import {
  DataTableComponent,
  DialogService,
  TableWidthConfig,
  IDrawerOpenResult,
  DrawerService,
} from '@devui';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';
import { LogComponent } from 'src/app/@shared/components/log/log.component';

@Component({
  selector: 'app-other-outbound',
  templateUrl: './other-outbound.component.html',
  styleUrls: ['./other-outbound.component.scss'],
})
export class OtherOutboundComponent {
  value1 = [];
  tableData: any[] = [];
  ingredientDetail: any[] = []; // 食材详情数据
  splitBarSize = '1px';
  partDetailHeight = '50%';
  OtherOutboundNum: string = '';
  DateTime: any = null;
  startTime: any = null;
  endTime: any = null;
  allCheckedStatus = false;
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20,
  };
  checkedIds = [];
  pageSizeOptions = [10, 20, 30, 50, 100];
  msgs: { severity: any; summary: any; content: any }[];
  config = {
    id: 'Add-role',
    maxHeight: '400px',
    width: '400px',
    backdropCloseable: true,
  }; //弹窗配置
  filterValue: string = '';
  TreeData: any = [];
  @ViewChild(DataTableComponent, { static: true })
  datatable: DataTableComponent;
  state: any;
  constructor(
    private dialogService: DialogService,
    private SharedMethodService: SharedMethodService,
    private Router: Router,
    private StorehouseService: StorehouseService,
    private DrawerService: DrawerService
  ) {}
  ngOnInit(): void {
    // 注意：这里使用入库服务来模拟出库功能，实际项目中需要创建专门的出库服务
    this.StorehouseService.GetOtherWarehousingModelsPaged(
      this.OtherOutboundNum,
      this.DateTime,
      this.startTime,
      this.endTime,
      this.pager.pageIndex,
      this.pager.pageSize
    ).subscribe((data: any) => {
      this.tableData = data.items;
      this.pager.total = data.totalCount;
    });
  }
  dataTableOptions = {
    columns: [
      {
        field: 'code',
        header: '出库单号',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '出库日期',
        fieldType: 'text',
      },
      {
        field: '状态',
        header: '出库状态',
        fieldType: 'text',
      },
      {
        field: '审核',
        header: '审核状态',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '备注',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '制单人',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '制单日期',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '日志',
        fieldType: 'text',
      },
    ],
  }; //表格数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px',
    },
    {
      field: 'name',
      width: '180px',
    },
    {
      field: 'name',
      width: '160px',
    },
    {
      field: 'name',
      width: '150px',
    },
    {
      field: 'name',
      width: '150px',
    },
    {
      field: 'name',
      width: '150px',
    },
    {
      field: 'name',
      width: '150px',
    },
    {
      field: 'name',
      width: '150px',
    },
    {
      field: 'name',
      width: '100px',
    },
    {
      field: 'name',
      width: '100px',
    },
  ]; //表格宽度配置

  // 食材出库详情表格宽度配置
  tableWidthConfig2: TableWidthConfig[] = [
    {
      field: 'ingredientCode',
      width: '120px'
    },
    {
      field: 'ingredientName',
      width: '150px'
    },
    {
      field: 'specification',
      width: '120px'
    },
    {
      field: 'description',
      width: '200px'
    },
    {
      field: 'quantity',
      width: '100px'
    },
    {
      field: 'unit',
      width: '80px'
    },
    {
      field: 'unitPrice',
      width: '100px'
    },
    {
      field: 'totalAmount',
      width: '120px'
    },
    {
      field: 'purpose',
      width: '120px'
    },
    {
      field: 'recipient',
      width: '100px'
    },
    {
      field: 'outboundDate',
      width: '120px'
    },
    {
      field: 'originalLocation',
      width: '120px'
    },
    {
      field: 'remark',
      width: '150px'
    }
  ];

  // 显示出库单详情
  showDetail(rowItem: any, rowIndex: number) {
    // 模拟获取食材出库详情数据，实际项目中应该调用后端API
    this.ingredientDetail = this.mockOutboundDetail(rowItem);
  }

  // 模拟食材出库详情数据
  mockOutboundDetail(orderItem: any) {
    return [
      {
        ingredientCode: 'FOOD001',
        ingredientName: '大白菜',
        specification: '500g/袋',
        description: '新鲜大白菜，产地山东',
        quantity: 30,
        unit: '袋',
        unitPrice: 3.50,
        totalAmount: 105.00,
        purpose: '炒菜机器人测试',
        recipient: '张三',
        outboundDate: new Date('2025-01-25'),
        originalLocation: 'A区-01-001',
        remark: '炒菜机器人专用测试食材'
      },
      {
        ingredientCode: 'FOOD002',
        ingredientName: '土豆',
        specification: '1kg/袋',
        description: '优质土豆，产地内蒙古',
        quantity: 20,
        unit: '袋',
        unitPrice: 4.20,
        totalAmount: 84.00,
        purpose: '炒菜机器人测试',
        recipient: '李四',
        outboundDate: new Date('2025-01-25'),
        originalLocation: 'A区-01-002',
        remark: '机器人配菜测试'
      },
      {
        ingredientCode: 'FOOD003',
        ingredientName: '胡萝卜',
        specification: '800g/袋',
        description: '新鲜胡萝卜，营养丰富',
        quantity: 25,
        unit: '袋',
        unitPrice: 2.80,
        totalAmount: 70.00,
        purpose: '炒菜机器人测试',
        recipient: '王五',
        outboundDate: new Date('2025-01-25'),
        originalLocation: 'A区-01-003',
        remark: '机器人辅料测试'
      }
    ];
  }
  pageIndexChange($event: any) {
    this.pager.pageIndex = $event;
    this.StorehouseService.GetOtherWarehousingModelsPaged(
      this.OtherOutboundNum,
      this.DateTime,
      this.startTime,
      this.endTime,
      this.pager.pageIndex,
      this.pager.pageSize
    ).subscribe((data: any) => {
      this.tableData = data.items;
      this.pager.total = data.totalCount;
    });
  } //切换页码
  pageSizeChange($event: any) {
    this.StorehouseService.GetOtherWarehousingModelsPaged(
      this.OtherOutboundNum,
      this.DateTime,
      this.startTime,
      this.endTime,
      this.pager.pageIndex,
      this.pager.pageSize
    ).subscribe((data: any) => {
      this.tableData = data.items;
      this.pager.total = data.totalCount;
    });
  } //改变每页显示数量
  DeleteRole(rowitem: any, dialogtype?: string) {
    const results = this.dialogService.open({
      ...this.config,
      title: '删除食材出库单',
      content: '确认删除该食材出库单据吗？',
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.StorehouseService.DeleteOtherWarehousingModel(
              rowitem.otherWarehousingModelId
            ).subscribe(
              (data: any) => {
                this.StorehouseService.getWarehouseById(
                  rowitem.warehouseId
                ).subscribe((data: any) => {
                  rowitem.warehouseName = data.warehouseName;
                });
                this.showToast('success', '成功', '食材出库单删除成功');
              },
              (error) => {
                if (error.status == 404) {
                  this.showToast('error', '失败', '服务器连接失败');
                } else {
                  this.showToast('error', '失败', error.error);
                }
              }
            );
            results.modalInstance.hide();
            this.StorehouseService.GetOtherWarehousingModelsPaged(
              this.OtherOutboundNum,
              this.DateTime,
              this.startTime,
              this.endTime,
              this.pager.pageIndex,
              this.pager.pageSize
            ).subscribe((data: any) => {
              this.tableData = data.items;
              this.pager.total = data.totalCount;
            });
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  } //删除食材出库单
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  } //提示框
  add() {
    this.Router.navigate(['/pages/inventory/other-outbound/add']);
  } //新增食材出库
  edit(id: any) {
    this.Router.navigate(['/pages/inventory/other-outbound/edit', id]);
  }
  filter() {
    this.StorehouseService.GetOtherWarehousingModelsPaged(
      this.OtherOutboundNum,
      this.DateTime,
      this.startTime,
      this.endTime,
      this.pager.pageIndex,
      this.pager.pageSize
    ).subscribe((data: any) => {
      this.tableData = data.items;
      this.pager.total = data.totalCount;
    });
  } //查询食材
  reset() {
    this.OtherOutboundNum = '';
    this.DateTime = null;
    this.startTime = null;
    this.endTime = null;
    this.value1 = [];
    this.StorehouseService.GetOtherWarehousingModelsPaged(
      this.OtherOutboundNum,
      this.DateTime,
      this.startTime,
      this.endTime,
      this.pager.pageIndex,
      this.pager.pageSize
    ).subscribe((data: any) => {
      this.tableData = data.items;
      this.pager.total = data.totalCount;
    });
  } //重置食材查询
  onRowCheckChange(
    checked: any,
    rowIndex: any,
    nestedIndex: any,
    rowItem: { $checked: any; $halfChecked: boolean }
  ) {
    this.SharedMethodService.onRowCheckChange(
      checked,
      rowIndex,
      nestedIndex,
      rowItem,
      this.datatable
    );
  }
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(
      this.datatable,
      'workshopId'
    ).subscribe((data: any) => {
      this.checkedIds = data;
    });
  } //获取选中行
  cleared() {
    this.SharedMethodService.cleared(
      this.checkedIds,
      this.tableData,
      this.datatable
    ).subscribe((data: any) => {
      this.checkedIds = data;
    });
  } //清空选中行
  start$end() {
    this.startTime = this.value1[0]
      .toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      })
      .replace(/\//g, '/');
    this.endTime = this.value1[1]
      .toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      })
      .replace(/\//g, '/');
  }
  detailed(id: any) {
    this.Router.navigate(['/pages/inventory/other-outbound/details', id]);
  }
  chuku(id: any) {
    this.StorehouseService.ReceiptOtherWarehousingItems(id).subscribe(
      (data: any) => {
        this.showToast('success', '成功', '食材出库成功');
        this.StorehouseService.GetOtherWarehousingModelsPaged(
          this.OtherOutboundNum,
          this.DateTime,
          this.startTime,
          this.endTime,
          this.pager.pageIndex,
          this.pager.pageSize
        ).subscribe((data: any) => {
          this.tableData = data.items;
          this.pager.total = data.totalCount;
        });
      },
      (error) => {
        if (error.status == 404) {
          this.showToast('error', '失败', '服务器连接失败');
        } else {
          this.showToast('error', '失败', error.error);
        }
      }
    );
  } //食材出库操作
  DownloadOtherWarehousingFileModel() {
    this.StorehouseService.DownloadOtherWarehousingFileModel().subscribe(
      (data: any) => {
        // 创建一个新的 Blob 对象
        const blob = new Blob([data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });

        // 创建一个指向 Blob 的 URL
        const url = window.URL.createObjectURL(blob);

        // 创建一个新的 <a> 元素并点击它来开始下载
        const link = document.createElement('a');
        link.href = url;
        link.download = '食材出库单模板.xlsx'; // 设置下载文件的名称
        link.click();

        // 释放 URL
        window.URL.revokeObjectURL(url);

        this.showToast('success', '成功', '下载成功');
      },
      (error) => {
        if (error.status == 404) {
          this.showToast('error', '失败', '服务器连接失败');
        } else {
          this.showToast('error', '失败', error.error);
        }
      }
    );
  } //下载食材出库模板
  onFileSelected(event: any) {
    const file = event.target.files[0];
    this.StorehouseService.ImportOtherWarehousingFromExcel(file).subscribe(
      (response) => {
        this.showToast('success', '成功', '食材出库数据导入成功');
        this.StorehouseService.GetOtherWarehousingModelsPaged(
          this.OtherOutboundNum,
          this.DateTime,
          this.startTime,
          this.endTime,
          this.pager.pageIndex,
          this.pager.pageSize
        ).subscribe((data: any) => {
          this.tableData = data.items;
          this.pager.total = data.totalCount;
        });
      },
      (error) => {
        if (error.status == 404) {
          this.showToast('error', '失败', '服务器连接失败');
        } else {
          this.showToast('error', '失败', error.error);
        }
      }
    );
    event.target.value = null; // 重置 input 元素的值
  }
  isAudit(rowitem: any) {
    this.StorehouseService.AuditOtherWarehousingModel(
      rowitem.otherWarehousingModelId
    ).subscribe(
      (data: any) => {
        this.showToast('success', '成功', '食材出库单审核成功');
        this.StorehouseService.GetOtherWarehousingModelsPaged(
          this.OtherOutboundNum,
          this.DateTime,
          this.startTime,
          this.endTime,
          this.pager.pageIndex,
          this.pager.pageSize
        ).subscribe((data: any) => {
          this.tableData = data.items;
          this.pager.total = data.totalCount;
        });
      },
      (error) => {
        if (error.status == 404) {
          this.showToast('error', '失败', '服务器连接失败');
        } else {
          this.showToast('error', '失败', error.error);
        }
      }
    );
  } //审核食材出库单
  results: IDrawerOpenResult;
  GetLogs() {
    this.StorehouseService.GetAllOtherWarehousingLogs(1, 9999).subscribe(
      (data: any) => {
        const logData = data.items;
        const columns = [
          {
            field: '食材出库单号',
            header: '食材出库单号',
            fieldType: 'text',
          },
          {
            field: 'content',
            header: '日志内容',
            fieldType: 'text',
          },
          {
            field: '执行人',
            header: '执行人',
            fieldType: 'text',
          },
          {
            field: '执行时间',
            header: '执行时间',
            fieldType: 'text',
          },
        ];

        this.results = this.DrawerService.open({
          drawerContentComponent: LogComponent,
          width: '40%',
          data: { data: logData, columns: columns },
          zIndex: 1000,
          isCover: false,
          fullScreen: true,
          backdropCloseable: true,
          escKeyCloseable: true,
          position: 'right',
          resizable: true,
          onClose: () => {},
        });
      }
    );
  }
  GetLogById(rowItem: any) {
    this.StorehouseService.GetLogsByOtherWarehousingId(
      rowItem.otherWarehousingModelId,
      1,
      9999
    ).subscribe((data: any) => {
      const logData = data.items;
      const columns = [
        {
          field: '食材出库单号',
          header: '食材出库单号',
          fieldType: 'text',
        },
        {
          field: 'content',
          header: '日志内容',
          fieldType: 'text',
        },
        {
          field: '执行人',
          header: '执行人',
          fieldType: 'text',
        },
        {
          field: '执行时间',
          header: '执行时间',
          fieldType: 'text',
        },
      ];

      this.results = this.DrawerService.open({
        drawerContentComponent: LogComponent,
        width: '40%',
        data: { data: logData, columns: columns },
        zIndex: 1000,
        isCover: false,
        fullScreen: true,
        backdropCloseable: true,
        escKeyCloseable: true,
        position: 'right',
        resizable: true,
        onClose: () => {},
      });
    });
  }
}
